package com.epalmpay.service.yunstream.impl;

import com.epalmpay.dto.bonus.BonusSendLogListOutDTO;
import com.epalmpay.dto.bonus.BonusSendLogOutDTO;
import com.epalmpay.dto.datareport.BaseReportInDTO;
import com.epalmpay.dto.datareport.ObdReportListOutDTO;
import com.epalmpay.dto.datareport.ObdReportOutDTO;
import com.epalmpay.dto.datareport.OilChargeReportListOutDTO;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.dto.yunliu.obd.*;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.enumdef.YunStreamEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.service.profitmanage.IProfitManageService;
import com.epalmpay.service.yunstream.IObdService;
import com.epalmpay.util.*;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import sun.management.resources.agent;

import javax.annotation.Resource;
import java.util.*;


@Service("obdService")
public class ObdServiceImpl implements IObdService {

	protected Logger logger = Logger.getLogger(this.getClass());

	@Resource
	private YsObdMapper ysObdMapper;
	@Resource
	private YsObdPurchaseApplyMapper ysObdPurchaseApplyMapper;
	@Resource
	private YsObdBatchMapper ysObdBatchMapper;
	@Resource
	private YsObdBatchItemMapper ysObdBatchItemMapper;
    @Resource
	private AgentMapper agentMapper;
	@Resource
	private ShopMapper shopMapper;
    @Resource
	private IProfitManageService profitManageService;
	@Resource
	private MemberMapper memberMapper;
	@Resource
	private YsObdPurchaseSetMapper ysObdPurchaseSetMapper;
	@Resource
	private TradeOfflineMapper tradeOfflineMapper;
	@Resource
	private GroupMapper groupMapper;
	@Resource
	private UserbaseMapper userbaseMapper;

	//获取obd设备库存列表
	@Override
	public ObdStoreListOutDTO getStoreList(ObdInDTO obdInDTO) throws Exception {
		ObdStoreListOutDTO obdStoreListOutDTO = new ObdStoreListOutDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		if(obdInDTO.getAgentId()!=null){
			param.put("agentId",obdInDTO.getAgentId());
		}
		else if(obdInDTO.getShopId()!=null){
			param.put("shopId",obdInDTO.getShopId());
		}
		else if(obdInDTO.getGroupId()!=null){
			param.put("groupId",obdInDTO.getGroupId());
		}

		//操作员以姓名形式显示
		List<Userbase> userlist = ysObdBatchMapper.selectCreaterList(param);
		for(Userbase ub : userlist) {
			int usertype = ub.getUserType();
			long userid = ub.getId();
			long groupid = ub.getGroupId();
			if(usertype == 1) {//如果是大商户或渠道则去t_group进行姓名查询
				Group group = groupMapper.selectByPrimaryKey(groupid);
				ub.setUsername(group.getMerchantName());
			} else if(usertype == 2||usertype == 3) {//直接取name
				ub.setUsername(ub.getName());
			} else if(usertype == 4) {//代理商
				Agent agent = agentMapper.selectUserId(userid);
				ub.setUsername(agent.getMerchantName());
			} else if(usertype == 5) {//门店
				Shop shop = shopMapper.selectUserId(userid);
				ub.setUsername(shop.getMerchantName());
			}
		}
        //取得入库操作员列表
		obdStoreListOutDTO.setUserbaseList(userlist);
		param.put("groupId",obdInDTO.getGroupId());
		param.put("agentId",obdInDTO.getAgentId());
		param.put("shopId",obdInDTO.getShopId());
		param.put("creater",obdInDTO.getCreater());
		param.put("startDate",obdInDTO.getStartDate());
		param.put("endDate",obdInDTO.getEndDate());
		param.put("name", obdInDTO.getName());

		int sumCount = ysObdMapper.selectObdStoreListCount(param);
		obdStoreListOutDTO.setStoreNum(sumCount);
		obdStoreListOutDTO.setSumCount(sumCount);
		if(sumCount<=0) {
			return obdStoreListOutDTO;
		}
		param.put("limit", obdInDTO.getPageSize());
		param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));
		
		List<ObdStoreOutDTO> obdStoreOutDTOList = ysObdMapper.selectObdStoreList(param);
		for(ObdStoreOutDTO osod: obdStoreOutDTOList) {
			long userid = osod.getCreater();
			Userbase ub = userbaseMapper.selectByPrimaryKey(userid);
			int usertype = ub.getUserType();
			long groupid = ub.getGroupId();
			if(usertype == 1) {//如果是大商户或渠道则去t_group进行姓名查询
				Group group = groupMapper.selectByPrimaryKey(groupid);
				osod.setCreaterName(group.getMerchantName());
			} else if(usertype == 2||usertype == 3) {//直接取name
				osod.setCreaterName(ub.getName());
			} else if(usertype == 4) {//代理商
				Agent agent = agentMapper.selectUserId(userid);
				osod.setCreaterName(agent.getMerchantName());
			} else if(usertype == 5) {//门店
				Shop shop = shopMapper.selectUserId(userid);
				osod.setCreaterName(shop.getMerchantName());
			}
		}
		obdStoreListOutDTO.setObdStoreOutDTOList(obdStoreOutDTOList);
		return obdStoreListOutDTO;
	}

	@Override
	public ObdPurchaseApplyListOutDTO getPurchaseApplayList(ObdInDTO obdInDTO) throws Exception {
		ObdPurchaseApplyListOutDTO obdPurchaseApplyListOutDTO = new ObdPurchaseApplyListOutDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		if(obdInDTO.getAgentId()!=null){
			param.put("agentId",obdInDTO.getAgentId());
		}
		if(obdInDTO.getShopId()!=null){
			param.put("shopId",obdInDTO.getShopId());
		}
		if(obdInDTO.getGroupId()!=null){
			param.put("groupId",obdInDTO.getGroupId());
		}

		param.put("startDate",obdInDTO.getStartDate());
		param.put("endDate",obdInDTO.getEndDate());
		param.put("status", obdInDTO.getApplayStatus());


		int sumCount = ysObdMapper.selectObdPurchaseApplyListCount(param);
		obdPurchaseApplyListOutDTO.setSumCount(sumCount);
		if (sumCount <= 0){
			return obdPurchaseApplyListOutDTO;
		}

		param.put("limit", obdInDTO.getPageSize());
		param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));

		List<ObdPurchaseApplyOutDTO> obdPurchaseApplyOutDTOS = ysObdMapper.selectObdPurchaseApplyList(param);
		obdPurchaseApplyListOutDTO.setObdPurchaseApplyOutDTOS(obdPurchaseApplyOutDTOS);



		return obdPurchaseApplyListOutDTO;
	}

	@Override
	public ObdApplyStepListOutDTO getOpertorApplayList(ObdInDTO obdInDTO) throws Exception {
		ObdApplyStepListOutDTO obdApplyStepListOutDTO = new ObdApplyStepListOutDTO();


		//获取采购步骤说明
		ObdPurchaseApplyOutDTO obdPurchaseApplyOutDTO = ysObdPurchaseApplyMapper.selectOpertorApplyById(obdInDTO.getId());

		if (obdPurchaseApplyOutDTO != null && !Tools.isEmpty(obdPurchaseApplyOutDTO.getOperatContent())){
			List<ObdApplayStepDTO> list = JSONUtils.fromJson(obdPurchaseApplyOutDTO.getOperatContent(), new TypeToken<List<ObdApplayStepDTO>>() {
			}.getType());
			if (list.size() <= 0){
				return obdApplyStepListOutDTO;
			}

			Collections.reverse(list);
			obdApplyStepListOutDTO.setSumCount(list.size());
			obdApplyStepListOutDTO.setObdApplayStepDTOS(list);
		}


		return obdApplyStepListOutDTO;
	}

	@Override
	public ObdPurchaseApplyOutDTO getObdSigleAmount(ObdInDTO obdInDTO) throws Exception {
		return ysObdMapper.selectObdAmountByGroupId(obdInDTO.getGroupId());
	}

	@Override
	public ObdSmOutDTO getObdSmUrl(ObdSmOutDTO obdSmOutDTO) throws Exception {

		//查询OBD 扫码商户号
//		YsObdPurchaseSet ysObdPurchaseSet = ysObdPurchaseSetMapper.selectByGroupId(obdSmOutDTO.getGroupId());
//		if (ysObdPurchaseSet !=  null){
			String url = obdSmOutDTO.getQrUrl() + "?" +//+ "fyMerchantId="+ysObdPurchaseSet.getScanMerchantCode() + "&" +
					"orderId="+obdSmOutDTO.getOrderId()+"&"+"realAmount="+obdSmOutDTO.getRealAmount();// +"&"+
//					"applyId=" + obdSmOutDTO.getApplyId();
			obdSmOutDTO.setQrUrl(url);
			return obdSmOutDTO;
//		}


//		return null;
	}

	@Override
	public ObdPurchaseApplyOutDTO getObdNumAndSigleAmount(ObdInDTO obdInDTO) throws Exception {
		return ysObdPurchaseApplyMapper.selectObdNumAndAmountById(obdInDTO.getId());
	}

	@Override
	public ObdPurchaseApplyOutDTO getObdLogisticsById(YsObdPurchaseApply data) throws ApplicationException {
		return ysObdPurchaseApplyMapper.selectApplayDetialById(data.getId());
	}

	@Override
	public int insertObdPurchaseApplay(YsObdPurchaseApply data) {
		data.setGmtCreate(new Date());
		data.setGmtModified(new Date());

		//添加操作步骤 保存为一个list
		List<ObdApplayStepDTO> list = new ArrayList<>();
		ObdApplayStepDTO step = new ObdApplayStepDTO();
		step.setUserName(data.getUserName());
		step.setTime(new Date());
		step.setContent("采购申请");
		list.add(step);

		data.setOperatContent(JSONUtils.toJson(list));


		return ysObdPurchaseApplyMapper.insertSelective(data);
	}

	@Override
	public int updateNumAndAmountApply(YsObdPurchaseApply data) {
		//获取采购步骤说明
		ObdPurchaseApplyOutDTO obdPurchaseApplyOutDTO = ysObdPurchaseApplyMapper.selectOpertorApplyById(data.getId());

		if (!Tools.isEmpty(obdPurchaseApplyOutDTO.getOperatContent())){
			List<ObdApplayStepDTO> stepList = new ArrayList<>();
			stepList = JSONUtils.fromJson(obdPurchaseApplyOutDTO.getOperatContent(), new TypeToken<List<ObdApplayStepDTO>>() {
			}.getType());
			ObdApplayStepDTO step = new ObdApplayStepDTO();
			step.setUserName(data.getUserName());
			step.setTime(new Date());
			step.setContent("修改申请数量或者单价");
			stepList.add(step);
			data.setOperatContent(JSONUtils.toJson(stepList));
		}
		data.setGmtModified(new Date());
		return ysObdPurchaseApplyMapper.updateByPrimaryKeySelective(data);
	}

	@Override
	public int updatePayType(YsObdPurchaseApply data) {


		//获取采购步骤说明
		ObdPurchaseApplyOutDTO obdPurchaseApplyOutDTO = ysObdPurchaseApplyMapper.selectOpertorApplyById(data.getId());

		if (!Tools.isEmpty(obdPurchaseApplyOutDTO.getOperatContent())){
			List<ObdApplayStepDTO> stepList = new ArrayList<>();
			stepList = JSONUtils.fromJson(obdPurchaseApplyOutDTO.getOperatContent(), new TypeToken<List<ObdApplayStepDTO>>() {
			}.getType());
			ObdApplayStepDTO step = new ObdApplayStepDTO();
			step.setUserName(data.getUserName());
			step.setTime(new Date());
			step.setContent("设置支付方式");
			if (data.getPayType() == YunStreamEnum.ObdPaymentType.Remit.getType()){
				step.setBack(YunStreamEnum.ObdPaymentType.Remit.getName());
			}else if (data.getPayType() == YunStreamEnum.ObdPaymentType.SM.getType()){
				step.setBack(YunStreamEnum.ObdPaymentType.SM.getName());
			}else if (data.getPayType() == YunStreamEnum.ObdPaymentType.Offline.getType()){
				step.setBack(YunStreamEnum.ObdPaymentType.Offline.getName());
			}
			stepList.add(step);
			data.setOperatContent(JSONUtils.toJson(stepList));
		}

		//如果是支付宝和微信,去交易表里插数据
		if (data.getPayType() == YunStreamEnum.ObdPaymentType.SM.getType()) {
			//1、查出数量和金额
			ObdPurchaseApplyOutDTO detial = ysObdPurchaseApplyMapper.selectApplayDetialById(data.getId());
			Integer totalAmt = detial.getAmount()*detial.getApplayNum();
			Integer orderAmt = detial.getOrderAmount();
			int count = totalAmt/orderAmt;
			Integer balancAmt = totalAmt%orderAmt;
			//商品订单
			List<String> orderId = new ArrayList<>();

			//这里金额是本身金额
			if (totalAmt%orderAmt != 0){
				String orderNo="OBD"+data.getId()+"YL"+DateUtil.getSdfTimes()+Tools.getRandomNum(4);
				orderId.add(orderNo);
				TradeOffline tradeOffline=new TradeOffline();
				tradeOffline.setGmtCreate(new Date());
				tradeOffline.setGmtModified(new Date());
				tradeOffline.setGroupId(detial.getGroupId());
				tradeOffline.setOrderId(orderNo);
				tradeOffline.setPayerId(null);//付款者id号
				tradeOffline.setPayerName(null);//付款者姓名
				tradeOffline.setPayerType(null);//付款者类型
				tradeOffline.setPayType((byte) BizEnum.PaymentType.Other.getType());//支付方式
				tradeOffline.setReceiverId(detial.getGroupId()+"");//接收者id
				tradeOffline.setReceiverName(detial.getGroupName());//接收者 此处以核销录入数据
				tradeOffline.setReceiverType((byte)CommonEnum.UserType.BusinessManager.getType());
				tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());//交易类型
				tradeOffline.setSubType((byte)BizEnum.PaymentScene.Scan.getType());//支付场景
				tradeOffline.setOrderAmount(balancAmt); //订单金额
				tradeOffline.setDiscountAmount(0);//折扣金额
				tradeOffline.setRealAmount(balancAmt);//实付金额
				tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.WaitingForPay.getType());//交易状态
				tradeOffline.setIsWallet(false);
				tradeOffline.setGoodType(null);//商品类型(线上用) ？
				tradeOffline.setMemo("OBD购买");
				tradeOffline.setDetail("用户使用支付宝或微信购买");
				tradeOffline.setMerchantNo(null);//商户号(对账用)
				tradeOffline.setTerminalNo(null);//商户终端号
				tradeOffline.setPayAccount("");//支付卡号
				tradeOffline.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
				tradeOffline.setCrcodeStr(null);
				tradeOffline.setOldOrderId(null);
				tradeOffline.setDividableAmount(0);//可分润金额
				tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
				tradeOffline.setPayOrderid(null);
				tradeOffline.setPayBakOrderid(null);
				tradeOffline.setInNetCompany(null);//入网机构
				tradeOfflineMapper.insertSelective(tradeOffline);
			}
			//整除后，交易额是 设定的拆单金额
			for (int i = 0; i < count; i++){
				String orderNo="OBD"+data.getId()+"YL"+DateUtil.getSdfTimes()+Tools.getRandomNum(4);
				orderId.add(orderNo);
				TradeOffline tradeOffline=new TradeOffline();
				tradeOffline.setGmtCreate(new Date());
				tradeOffline.setGmtModified(new Date());
				tradeOffline.setGroupId(detial.getGroupId());
				tradeOffline.setOrderId(orderNo);
				tradeOffline.setPayerId(null);//付款者id号
				tradeOffline.setPayerName(null);//付款者姓名
				tradeOffline.setPayerType(null);//付款者类型
				tradeOffline.setPayType((byte) BizEnum.PaymentType.Other.getType());//支付方式
				tradeOffline.setReceiverId(detial.getGroupId()+"");//接收者id
				tradeOffline.setReceiverName(detial.getGroupName());//接收者 此处以核销录入数据
				tradeOffline.setReceiverType((byte)CommonEnum.UserType.BusinessManager.getType());
				tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());//交易类型
				tradeOffline.setSubType((byte)BizEnum.PaymentScene.Scan.getType());//支付场景
				tradeOffline.setOrderAmount(orderAmt); //订单金额
				tradeOffline.setDiscountAmount(0);//折扣金额
				tradeOffline.setRealAmount(orderAmt);//实付金额
				tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.WaitingForPay.getType());//交易状态
				tradeOffline.setIsWallet(false);
				tradeOffline.setGoodType(null);//商品类型(线上用) ？
				tradeOffline.setMemo("OBD购买");
				tradeOffline.setDetail("用户使用支付宝或微信购买");
				tradeOffline.setMerchantNo(null);//商户号(对账用)
				tradeOffline.setTerminalNo(null);//商户终端号
				tradeOffline.setPayAccount("");//支付卡号
				tradeOffline.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
				tradeOffline.setCrcodeStr(null);
				tradeOffline.setOldOrderId(null);
				tradeOffline.setDividableAmount(0);//可分润金额
				tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
				tradeOffline.setPayOrderid(null);
				tradeOffline.setPayBakOrderid(null);
				tradeOffline.setInNetCompany(null);//入网机构
				tradeOfflineMapper.insertSelective(tradeOffline);
			}

			data.setOrderId(JSONUtils.toJson(orderId));
		}


		data.setGmtModified(new Date());
		return ysObdPurchaseApplyMapper.updateByPrimaryKeySelective(data);
	}


	@Override
	public int updateRemitCommit(YsObdPurchaseApply data) {
		//获取采购步骤说明
		ObdPurchaseApplyOutDTO obdPurchaseApplyOutDTO = ysObdPurchaseApplyMapper.selectOpertorApplyById(data.getId());

		if (!Tools.isEmpty(obdPurchaseApplyOutDTO.getOperatContent())){
			List<ObdApplayStepDTO> stepList = new ArrayList<>();
			stepList = JSONUtils.fromJson(obdPurchaseApplyOutDTO.getOperatContent(), new TypeToken<List<ObdApplayStepDTO>>() {
			}.getType());
			ObdApplayStepDTO step = new ObdApplayStepDTO();
			step.setUserName(data.getUserName());
			step.setTime(new Date());
			step.setContent("支付");
			step.setBack(data.getOperatContent());
			stepList.add(step);
			//这里会把上面的覆盖掉
			data.setOperatContent(JSONUtils.toJson(stepList));
		}

		data.setGmtModified(new Date());
		return ysObdPurchaseApplyMapper.updateByPrimaryKeySelective(data);
	}

	@Override
	public int confirmPayCommit(YsObdPurchaseApply data) {
		//获取采购步骤说明
		ObdPurchaseApplyOutDTO obdPurchaseApplyOutDTO = ysObdPurchaseApplyMapper.selectOpertorApplyById(data.getId());

		if (!Tools.isEmpty(obdPurchaseApplyOutDTO.getOperatContent())){
			List<ObdApplayStepDTO> stepList = new ArrayList<>();
			stepList = JSONUtils.fromJson(obdPurchaseApplyOutDTO.getOperatContent(), new TypeToken<List<ObdApplayStepDTO>>() {
			}.getType());
			ObdApplayStepDTO step = new ObdApplayStepDTO();
			step.setUserName(data.getUserName());
			step.setTime(new Date());
			step.setContent("确认收款");
			if (data.getPayType() == YunStreamEnum.ObdPaymentType.Remit.getType()){
				step.setBack(YunStreamEnum.ObdPaymentType.Remit.getName());
			}else if (data.getPayType() == YunStreamEnum.ObdPaymentType.SM.getType()){
				step.setBack(YunStreamEnum.ObdPaymentType.SM.getName());
			}else if (data.getPayType() == YunStreamEnum.ObdPaymentType.Offline.getType()){
				step.setBack(YunStreamEnum.ObdPaymentType.Offline.getName());
			}

			stepList.add(step);
			data.setOperatContent(JSONUtils.toJson(stepList));
		}

		data.setGmtModified(new Date());
		return ysObdPurchaseApplyMapper.updateByPrimaryKeySelective(data);
	}


	@Override
	public int updateLogistics(YsObdPurchaseApply data) {
		//获取采购步骤说明
		ObdPurchaseApplyOutDTO obdPurchaseApplyOutDTO = ysObdPurchaseApplyMapper.selectOpertorApplyById(data.getId());

		if (!Tools.isEmpty(obdPurchaseApplyOutDTO.getOperatContent())){
			List<ObdApplayStepDTO> stepList = new ArrayList<>();
			stepList = JSONUtils.fromJson(obdPurchaseApplyOutDTO.getOperatContent(), new TypeToken<List<ObdApplayStepDTO>>() {
			}.getType());
			ObdApplayStepDTO step = new ObdApplayStepDTO();
			step.setUserName(data.getUserName());
			step.setTime(new Date());
			step.setContent("添加物流单号");
			stepList.add(step);
			data.setOperatContent(JSONUtils.toJson(stepList));
		}

		data.setGmtModified(new Date());
		return ysObdPurchaseApplyMapper.updateByPrimaryKeySelective(data);
	}

	@Override
	public int updatePurchaseApplyStatus(YsObdPurchaseApply data) {
		YsObdPurchaseApply ysObdPurchaseApply = new YsObdPurchaseApply();
		ysObdPurchaseApply.setId(data.getId());
		ysObdPurchaseApply.setGmtModified(new Date());
		ysObdPurchaseApply.setStatus(data.getStatus());
		ysObdPurchaseApply.setAuditStatus(data.getAuditStatus());
		ysObdPurchaseApply.setAuditTime(new Date());

		//获取采购步骤说明
		ObdPurchaseApplyOutDTO obdPurchaseApplyOutDTO = ysObdPurchaseApplyMapper.selectOpertorApplyById(data.getId());

		if (!Tools.isEmpty(obdPurchaseApplyOutDTO.getOperatContent())){
			List<ObdApplayStepDTO> stepList = new ArrayList<>();
			stepList = JSONUtils.fromJson(obdPurchaseApplyOutDTO.getOperatContent(), new TypeToken<List<ObdApplayStepDTO>>() {
			}.getType());

			ObdApplayStepDTO step = new ObdApplayStepDTO();
			step.setUserName(data.getUserName());
			step.setTime(new Date());
			if (data.getStatus() == YunStreamEnum.OBDPurchaseStatus.Closed.getType()){
				step.setContent("取消采购申请");
			}else if (data.getStatus() == YunStreamEnum.OBDPurchaseStatus.AuditRefuse.getType()){
				step.setContent("审核拒绝");
			}else if (data.getStatus() == YunStreamEnum.OBDPurchaseStatus.Dealed.getType()){
				step.setContent("处理完成");
			}
			stepList.add(step);
			ysObdPurchaseApply.setOperatContent(JSONUtils.toJson(stepList));
		}
		return ysObdPurchaseApplyMapper.updateByPrimaryKeySelective(ysObdPurchaseApply);
	}

	@Override
	public ObdPurchaseApplyOutDTO getObdApplayInfo(Long id) throws Exception {
		return ysObdPurchaseApplyMapper.selectApplayDetialById(id);
	}

	@Override
	public int deleteObd(ObdInDTO obdInDTO) throws Exception{
		YsObd ysObd = new YsObd();
		ysObd.setId(obdInDTO.getId());
		ysObd.setGmtModified(new Date());
		ysObd.setIsValid(Boolean.FALSE);
		return ysObdMapper.updateByPrimaryKeySelective(ysObd);
	}

	@Override
	public int deleteObdForBatch(ObdAddInDTO obdAddInDTO) throws Exception{

		int result =0;

		String[] deviceIdList = obdAddInDTO.getDeviceNo().split(",");
		if (deviceIdList.length < 0) {
			return 0;
		}
		List<YsObd> ysObdList = new ArrayList<YsObd>();
		//数据检查
		for (int i = 0; i < deviceIdList.length; i++) {

			YsObd ysObdOld = ysObdMapper.selectObdByDeviceId(deviceIdList[i]);
			if (ysObdOld == null) {
				throw new ApplicationException("设备ID:" + deviceIdList[i] + "的记录不存在！");
			}
			if (ysObdOld.getAgentId() != null || ysObdOld.getShopId() != null) {
				throw new ApplicationException("设备ID:" + deviceIdList[i] + "的记录已经分配！");
			}
			if (ysObdOld.getDeviceStatus() != null && ysObdOld.getDeviceStatus() == 1) {
				throw new ApplicationException("设备ID:" + deviceIdList[i] + "的记录已经激活！");
			}
			if (ysObdOld.getDeviceStatus() != null && ysObdOld.getDeviceStatus() == 2) {
				throw new ApplicationException("设备ID:" + deviceIdList[i] + "的记录已故障！");
			}
			ysObdList.add(ysObdOld);
		}

		Date date = new Date();

		//插入批次总表
		YsObdBatch ysObdBatch = new YsObdBatch();
		ysObdBatch.setGmtCreate(date);
		ysObdBatch.setGmtModified(date);
		ysObdBatch.setGroupId(obdAddInDTO.getGroupId());
		ysObdBatch.setCreater(obdAddInDTO.getLoginId());
		ysObdBatch.setOperateType(YunStreamEnum.OBDOperateType.BatchDelete.getType());
		ysObdBatch.setBatchNum(deviceIdList.length);
		ysObdBatch.setReceiverGroupId(obdAddInDTO.getGroupId());
		result = ysObdBatchMapper.insert(ysObdBatch);

		// 插入批次明细表 并更新obd表
		for (YsObd ysObd:ysObdList) {
			//插入批次明细
			YsObdBatchItem ysObdBatchItem = new YsObdBatchItem();
			ysObdBatchItem.setGroupId(obdAddInDTO.getGroupId());
			ysObdBatchItem.setGmtCreate(date);
			ysObdBatchItem.setCreater(obdAddInDTO.getLoginId());
			ysObdBatchItem.setGmtModified(date);
			ysObdBatchItem.setBatchId(ysObdBatch.getId());
			ysObdBatchItem.setObdId(ysObd.getId());
			result = ysObdBatchItemMapper.insert(ysObdBatchItem);

			//更新obd
			YsObd ysObdUpdate = new YsObd();
			ysObdUpdate.setId(ysObd.getId());
			ysObdUpdate.setGmtModified(new Date());
			ysObdUpdate.setIsValid(Boolean.FALSE);
			result = ysObdMapper.updateByPrimaryKeySelective(ysObdUpdate);
		}

		return 0;
	}

	//获取obd设备入库批次列表
	@Override
	public ObdStoreListOutDTO getStoreBatchList(ObdInDTO obdInDTO) throws Exception {
		ObdStoreListOutDTO obdStoreListOutDTO = new ObdStoreListOutDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		if(obdInDTO.getAgentId()!=null){
			param.put("agentId",obdInDTO.getAgentId());
		}
		else if(obdInDTO.getShopId()!=null){
			param.put("shopId",obdInDTO.getShopId());
		}
		else if(obdInDTO.getGroupId()!=null){
			param.put("groupId",obdInDTO.getGroupId());
		}
		//取得入库操作员列表
		obdStoreListOutDTO.setUserbaseList(ysObdBatchMapper.selectCreaterList(param));
		//param.put("groupId",obdInDTO.getGroupId());
		//param.put("agentId",obdInDTO.getAgentId());
		//param.put("shopId",obdInDTO.getShopId());
		param.put("creater",obdInDTO.getCreater());
		param.put("startDate",obdInDTO.getStartDate());
		param.put("endDate",obdInDTO.getEndDate());
		param.put("operateType",obdInDTO.getOperateType());

		int sumCount = ysObdBatchMapper.selectObdStoreBatchListCount(param);
		//obdStoreListOutDTO.setStoreNum(sumCount);
		obdStoreListOutDTO.setSumCount(sumCount);
		if(sumCount<=0) {
			return obdStoreListOutDTO;
		}
		param.put("limit", obdInDTO.getPageSize());
		param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));

		List<YsObdBatch> ysObdBatchList = ysObdBatchMapper.selectObdStoreBatchList(param);
		obdStoreListOutDTO.setYsObdBatchList(ysObdBatchList);
		return obdStoreListOutDTO;
	}

	@Override
	public ObdStoreListOutDTO getStoreBatchItemList(ObdInDTO obdInDTO) throws Exception {
		ObdStoreListOutDTO obdStoreListOutDTO = new ObdStoreListOutDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId",obdInDTO.getGroupId());
		param.put("batchId",obdInDTO.getBatchId());
		param.put("name", obdInDTO.getName());

		int sumCount = ysObdBatchItemMapper.selectObdstoreBatchItemListCount(param);
		obdStoreListOutDTO.setSumCount(sumCount);
		if(sumCount<=0) {
			return obdStoreListOutDTO;
		}
		param.put("limit", obdInDTO.getPageSize());
		param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));

		List<ObdStoreOutDTO> obdStoreOutDTOList = ysObdBatchItemMapper.selectObdstoreBatchItemList(param);
		obdStoreListOutDTO.setObdStoreOutDTOList(obdStoreOutDTOList);
		return obdStoreListOutDTO;
	}

	@Override
	public ObdDistributionListOutDTO getDistributionList(ObdInDTO obdInDTO) throws Exception{
		ObdDistributionListOutDTO obdDistributionListOutDTO = new ObdDistributionListOutDTO();

		Map<String,Object> param = new HashMap<String,Object>();
		if(obdInDTO.getLoginAgentId()!=null) {//如果登陆账号是代理商
			if (obdInDTO.getLoginAgentId() == obdInDTO.getAgentId()) {//如果查询全部
				param.put("loginAgentId", obdInDTO.getLoginAgentId());
				obdInDTO.setAgentId(obdInDTO.getLoginAgentId());
			} else {//如果查询某个代理商
				param.put("loginAgentId", obdInDTO.getLoginAgentId());
			}
		} else {//如果登陆账号是渠道
			if (obdInDTO.getLoginAgentId() == obdInDTO.getAgentId()) {//如果查询全部
				param.put("loginAgentId", null);
			} else {//如果查询某个代理商
				param.put("loginAgentId", obdInDTO.getAgentId());
			}
		}
			//取得代理商列表
			//obdDistributionListOutDTO.setAgentList(agentMapper.getAgentIdAndName(obdInDTO.getGroupId()));
			obdDistributionListOutDTO.setAgentList(agentMapper.getAllSubAgentByAgentId(obdInDTO.getLoginAgentId(),obdInDTO.getGroupId()));
			//取得子代理列表
            String subAgentStr = agentMapper.getAllSubAgentStrByAgentId(obdInDTO.getAgentId(),obdInDTO.getGroupId());
            //取得子门店列表
			String subShopStr = shopMapper.getAllSubShopStrByAgentId(obdInDTO.getAgentId(),obdInDTO.getGroupId());

			param.put("groupId",obdInDTO.getGroupId());
			//param.put("loginAgentId",obdInDTO.getLoginAgentId());
			//if(obdInDTO.getLoginAgentId() != null) {
				param.put("subAgentStr", obdInDTO.getAgentId() + "," + subAgentStr);
			//} else {
			//	param.put("subAgentStr", subAgentStr);
			//}
			param.put("subShopStr",subShopStr);
			//param.put("agentId",obdInDTO.getAgentId());
			//param.put("distributionStatus",obdInDTO.getDistributionStatus());
			param.put("activateStatus",obdInDTO.getActivateStatus());
			param.put("startDate",obdInDTO.getStartDate());
			param.put("endDate",obdInDTO.getEndDate());
			param.put("name", obdInDTO.getName());

			Map<String,Object> countMap = ysObdMapper.selectObdAgentDistributionListCount(param);
			Long sumCount = (Long)countMap.get("distributionNum");
			Long activateCount = (Long)countMap.get("activateCount");
			//obdStoreListOutDTO.setStoreNum(sumCount);
			obdDistributionListOutDTO.setDistributionNum(sumCount.intValue());
			obdDistributionListOutDTO.setSumCount(sumCount.intValue());
			//int activateCount = ysObdMapper.selectObdAgentActivateCount(param);
			obdDistributionListOutDTO.setActivateNum(activateCount.intValue());
			if(sumCount == null || sumCount <= 0) {
				return obdDistributionListOutDTO;
			}
			param.put("limit", obdInDTO.getPageSize());
			param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));

			List<YsObd> ysObdList = ysObdMapper.selectObdAgentDistributionList(param);
			obdDistributionListOutDTO.setYsObdList(ysObdList);

		/*}else {
			//取得代理商列表
			obdDistributionListOutDTO.setAgentList(agentMapper.getAgentIdAndName(obdInDTO.getGroupId()));
			param.put("groupId",obdInDTO.getGroupId());
			param.put("agentId",obdInDTO.getAgentId());
			param.put("distributionStatus",obdInDTO.getDistributionStatus());
			param.put("activateStatus",obdInDTO.getActivateStatus());
			param.put("startDate",obdInDTO.getStartDate());
			param.put("endDate",obdInDTO.getEndDate());
			param.put("name", obdInDTO.getName());

			int sumCount = ysObdMapper.selectObdDistributionListCount(param);
			//obdStoreListOutDTO.setStoreNum(sumCount);
			obdDistributionListOutDTO.setDistributionNum(sumCount);
			obdDistributionListOutDTO.setSumCount(sumCount);
			int activateCount = ysObdMapper.selectObdActivateCount(param);
			obdDistributionListOutDTO.setActivateNum(activateCount);
			if(sumCount<=0) {
				return obdDistributionListOutDTO;
			}
			param.put("limit", obdInDTO.getPageSize());
			param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));

			List<YsObd> ysObdList = ysObdMapper.selectObdDistributionList(param);
			obdDistributionListOutDTO.setYsObdList(ysObdList);

		}*/
		return obdDistributionListOutDTO;

	}

	@Override
	public int deleteObdDistribution(ObdInDTO obdInDTO) throws Exception{
		return ysObdMapper.updateDelDistribution(obdInDTO.getId(),obdInDTO.getAgentId());
	}

	//批量召回
	@Override
	public int deleteDistributeForBatch(ObdAddInDTO obdAddInDTO) throws Exception{
		int result =0;

		String[] deviceIdList = obdAddInDTO.getDeviceNo().split(",");
		if (deviceIdList.length < 0) {
			return 0;
		}
		List<YsObd> ysObdList = new ArrayList<YsObd>();
		//数据检查
		for (int i = 0; i < deviceIdList.length; i++) {

			YsObd ysObdOld = ysObdMapper.selectObdByDeviceId(deviceIdList[i]);
			if (ysObdOld == null) {
				throw new ApplicationException("设备ID:" + deviceIdList[i] + "的记录不存在！");
			}
			if (ysObdOld.getDeviceStatus() != null && ysObdOld.getDeviceStatus() == 1) {
				throw new ApplicationException("设备ID:" + deviceIdList[i] + "的记录已经激活！");
			}
			if (ysObdOld.getDeviceStatus() != null && ysObdOld.getDeviceStatus() == 2) {
				throw new ApplicationException("设备ID:" + deviceIdList[i] + "的记录已故障！");
			}
			if (ysObdOld.getAgentId() == null && ysObdOld.getShopId() == null) {
				throw new ApplicationException("设备ID:" + deviceIdList[i] + "的记录尚未分配！");
			}
			ysObdList.add(ysObdOld);
		}

		Date date = new Date();

		//插入批次总表
		YsObdBatch ysObdBatch = new YsObdBatch();
		ysObdBatch.setGmtCreate(date);
		ysObdBatch.setGmtModified(date);
		ysObdBatch.setGroupId(obdAddInDTO.getGroupId());
		ysObdBatch.setCreater(obdAddInDTO.getLoginId());
		ysObdBatch.setOperateType(YunStreamEnum.OBDOperateType.Recall.getType());
		ysObdBatch.setBatchNum(deviceIdList.length);
		ysObdBatch.setSendGroupId(obdAddInDTO.getGroupId());
		result = ysObdBatchMapper.insert(ysObdBatch);

		// 插入批次明细表 并更新obd表
		for (YsObd ysObd:ysObdList) {
			//插入批次明细
			YsObdBatchItem ysObdBatchItem = new YsObdBatchItem();
			ysObdBatchItem.setGroupId(obdAddInDTO.getGroupId());
			ysObdBatchItem.setGmtCreate(date);
			ysObdBatchItem.setCreater(obdAddInDTO.getLoginId());
			ysObdBatchItem.setGmtModified(date);
			ysObdBatchItem.setBatchId(ysObdBatch.getId());
			ysObdBatchItem.setObdId(ysObd.getId());
			result = ysObdBatchItemMapper.insert(ysObdBatchItem);

			//更新obd
			result = ysObdMapper.updateDelDistribution(ysObd.getId(),null);
		}

		return 0;
	}

	@Override
	public ObdDistributionListOutDTO getDistributionBatchList(ObdInDTO obdInDTO) throws Exception{
		ObdDistributionListOutDTO obdDistributionListOutDTO = new ObdDistributionListOutDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		if(obdInDTO.getAgentId()!=null){
			param.put("agentId",obdInDTO.getAgentId());
		}else {
			param.put("groupId", obdInDTO.getGroupId());
		}
		//取得入库操作员列表
		obdDistributionListOutDTO.setUserbaseList(ysObdBatchMapper.selectDistributionCreaterList(param));
		param.put("creater",obdInDTO.getCreater());
		param.put("operateType",obdInDTO.getOperateType());
		param.put("startDate",obdInDTO.getStartDate());
		param.put("endDate",obdInDTO.getEndDate());

		int sumCount = ysObdBatchMapper.selectObdDistributionBatchListCount(param);
		//obdStoreListOutDTO.setStoreNum(sumCount);
		obdDistributionListOutDTO.setSumCount(sumCount);
		if(sumCount<=0) {
			return obdDistributionListOutDTO;
		}
		param.put("limit", obdInDTO.getPageSize());
		param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));

		List<YsObdBatch> ysObdBatchList = ysObdBatchMapper.selectObdDistributionBatchList(param);
		obdDistributionListOutDTO.setYsObdBatchList(ysObdBatchList);
		return obdDistributionListOutDTO;
	}

	@Override
	public ObdDistributionListOutDTO  getDistributionBatchItemList(ObdInDTO obdInDTO) throws Exception{
		ObdDistributionListOutDTO obdDistributionListOutDTO = new ObdDistributionListOutDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId",obdInDTO.getGroupId());
		param.put("batchId",obdInDTO.getBatchId());
		param.put("name", obdInDTO.getName());

		int sumCount = ysObdBatchItemMapper.selectObdDistributionBatchItemListCount(param);
		obdDistributionListOutDTO.setSumCount(sumCount);
		if(sumCount<=0) {
			return obdDistributionListOutDTO;
		}
		param.put("limit", obdInDTO.getPageSize());
		param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));

		List<ObdDistributionOutDTO> obdDistributionOutDTOList = ysObdBatchItemMapper.selectObdDistributionBatchItemList(param);
		obdDistributionListOutDTO.setObdDistributionOutDTOList(obdDistributionOutDTOList);
		return obdDistributionListOutDTO;
	}

	@Override
	public ObdDetailOutDTO getObdDetail(ObdInDTO obdInDTO) throws Exception{
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("id",obdInDTO.getId());
        if(obdInDTO.getAgentId()!=null){
			param.put("agentId",obdInDTO.getAgentId());
		}else {
			param.put("groupId", obdInDTO.getGroupId());
		}

        return ysObdMapper.selectObdDetailById(param);
	}

	@Override
	public ObdOutDTO toObdStoreAdd(ObdAddInDTO obdAddInDTO) throws Exception{
		ObdOutDTO obdOutDTO = new ObdOutDTO();
		if(obdAddInDTO.getAgentId()==null) {
			obdOutDTO.setAgentList(agentMapper.getAgentIdAndName(obdAddInDTO.getGroupId()));
			obdOutDTO.setShopList(shopMapper.listShopByGroupId(obdAddInDTO.getGroupId()));
		}else{//代理登录
			obdOutDTO.setAgentList(agentMapper.getAllSubAgentByAgentId(obdAddInDTO.getAgentId(),obdAddInDTO.getGroupId()));
			obdOutDTO.setShopList(shopMapper.getAllSubShopByAgentId(obdAddInDTO.getAgentId(),obdAddInDTO.getGroupId()));
		}
		return obdOutDTO;
	}

	@Override
	public int addStore(ObdAddInDTO obdAddInDTO) throws Exception {
		int result = 0;

		List<YsObd> ysObdList = new ArrayList<YsObd>();
		Date date = new Date();
		Set<String> deviceidset = new HashSet<String>();

		String[] deviceIdandSimList = obdAddInDTO.getDeviceNo().split(",");
		if (deviceIdandSimList.length < 0) {
			return 0;
		}

		for (int i = 0; i < deviceIdandSimList.length; i++) {
			YsObd ysObd = new YsObd();
			try {
				String[] deviceIdandSim = deviceIdandSimList[i].split("#");
				if(deviceidset.contains(deviceIdandSim[0])) {
                    logger.info("设备ID:" + deviceIdandSim[0] + "的记录已经存在！");
				    continue;
                } else {
                    deviceidset.add(deviceIdandSim[0]);
                    ysObd.setDeviceId(deviceIdandSim[0]);
                    if (StringUtil.notEmpty(deviceIdandSim[1])) {
                        ysObd.setSimNo(deviceIdandSim[1]);
                    }
                    YsObd ysObdOld = ysObdMapper.selectObdByDeviceId(ysObd.getDeviceId());
                    if (ysObdOld != null) {
                        //对设备状态进行更新
                        ysObdMapper.updateOBDValid(ysObdOld);
                        //throw new ApplicationException("设备ID:" + ysObd.getDeviceId() + "的记录已经存在！");
                        logger.info("设备ID:" + ysObd.getDeviceId() + "的记录已经存在！");
                        continue;
                    }
                    ysObdList.add(ysObd);
                }
			}catch(Exception e){
				throw new ApplicationException("格式错误！");
			}
		}

		if(ysObdList.size() == 0)
			return 0;

		//插入Group入库批次
		YsObdBatch ysObdBatch = new YsObdBatch();
		ysObdBatch.setGroupId(obdAddInDTO.getGroupId());
		ysObdBatch.setGmtCreate(date);
		ysObdBatch.setGmtModified(date);
		ysObdBatch.setCreater(obdAddInDTO.getLoginId());
		ysObdBatch.setDeviceVersion(obdAddInDTO.getDeviceVersion());
		ysObdBatch.setOperateType(YunStreamEnum.OBDOperateType.InStore.getType());//入库
		ysObdBatch.setBatchNum(ysObdList.size());
		//ysObdBatch.setDistributionTime(date);
		ysObdBatch.setReceiverGroupId(obdAddInDTO.getGroupId());
		ysObdBatchMapper.insert(ysObdBatch);

		//插入obd明细
		for(YsObd ysObd:ysObdList){
			ysObd.setGroupId(obdAddInDTO.getGroupId());
			ysObd.setGmtCreate(date);
			ysObd.setGmtModified(date);
			ysObd.setCreater(obdAddInDTO.getLoginId());
			ysObd.setDeviceVersion(obdAddInDTO.getDeviceVersion());
			ysObd.setIsValid(Boolean.TRUE);
			//同时分配了
			if(obdAddInDTO.getAgentId()!=null||obdAddInDTO.getShopId()!=null) {
				ysObd.setDistributionTime(date);
				ysObd.setAgentId(obdAddInDTO.getAgentId());
				ysObd.setShopId(obdAddInDTO.getShopId());
			}
			ysObd.setDeviceStatus(YunStreamEnum.OBDActivateStatus.UnActivated.getType());		
			//插入obd明细
			ysObdMapper.insert(ysObd);

			//插入批次明细
			YsObdBatchItem ysObdBatchItem = new YsObdBatchItem();
			ysObdBatchItem.setGroupId(obdAddInDTO.getGroupId());
			ysObdBatchItem.setGmtCreate(date);
			ysObdBatchItem.setCreater(obdAddInDTO.getLoginId());
			ysObdBatchItem.setGmtModified(date);
			ysObdBatchItem.setBatchId(ysObdBatch.getId());
			ysObdBatchItem.setObdId(ysObd.getId());
			ysObdBatchItemMapper.insert(ysObdBatchItem);
		}

		//插入分配批次与明细
		if(obdAddInDTO.getAgentId()!=null||obdAddInDTO.getShopId()!=null) {
			//插入Group分配批次
			YsObdBatch ysObdDistributionBatch = new YsObdBatch();
			ysObdDistributionBatch.setGroupId(obdAddInDTO.getGroupId());
			ysObdDistributionBatch.setGmtCreate(date);
			ysObdDistributionBatch.setGmtModified(date);
			ysObdDistributionBatch.setCreater(obdAddInDTO.getLoginId());
			ysObdDistributionBatch.setDeviceVersion(obdAddInDTO.getDeviceVersion());
			ysObdDistributionBatch.setOperateType(YunStreamEnum.OBDOperateType.Distribution.getType());//分配
			ysObdDistributionBatch.setBatchNum(ysObdList.size());
			ysObdDistributionBatch.setDistributionTime(date);
			ysObdDistributionBatch.setSendGroupId(obdAddInDTO.getGroupId());
			ysObdDistributionBatch.setReceiverAgentId(obdAddInDTO.getAgentId());
			ysObdDistributionBatch.setReceiverShopId(obdAddInDTO.getShopId());
			ysObdBatchMapper.insert(ysObdDistributionBatch);

			//插入Group分配批次明细
			for (YsObd ysObd : ysObdList) {
				//插入批次明细
				YsObdBatchItem ysObdDistributionBatchItem = new YsObdBatchItem();
				ysObdDistributionBatchItem.setGroupId(obdAddInDTO.getGroupId());
				ysObdDistributionBatchItem.setGmtCreate(date);
				ysObdDistributionBatchItem.setCreater(obdAddInDTO.getLoginId());
				ysObdDistributionBatchItem.setGmtModified(date);
				ysObdDistributionBatchItem.setBatchId(ysObdDistributionBatch.getId());
				ysObdDistributionBatchItem.setObdId(ysObd.getId());
				ysObdBatchItemMapper.insert(ysObdDistributionBatchItem);
			}
		}

        return result;
	}

	//设备分配
	@Override
	public int addDeviceDistribution(ObdAddInDTO obdAddInDTO) throws Exception{
		int result = 0;

		List<YsObd> ysObdList = new ArrayList<YsObd>();
		Date date = new Date();

		String[] deviceIdList = obdAddInDTO.getDeviceNo().split(",");
		if(deviceIdList.length <0) {
			return 0;
		}
		for(int i=0;i<deviceIdList.length;i++){
			YsObd ysObd = new YsObd();
			ysObd.setDeviceId(deviceIdList[i]);
			YsObd ysObdOld = ysObdMapper.selectObdByDeviceId(ysObd.getDeviceId());
			if(ysObdOld==null||!ysObdOld.getIsValid()) {
				throw new ApplicationException("设备ID:" + ysObd.getDeviceId() + "的记录不存在！");
			}
			ysObd.setId(ysObdOld.getId());//取得id值
			//判断是否已经分配
			if(obdAddInDTO.getSendAgentId()!=null) {
				ysObdOld = ysObdMapper.selectDistributionObdByAgentIdAndDeviceId(ysObd.getDeviceId(),obdAddInDTO.getSendAgentId());
			}else{
				ysObdOld = ysObdMapper.selectDistributionObdByGroupIdAndDeviceId(ysObd.getDeviceId(),obdAddInDTO.getGroupId());
			}
			if(ysObdOld != null) {
				//throw new ApplicationException("设备ID:" + ysObd.getDeviceId() + "的记录已经分配！");
				logger.info("设备ID:" + ysObd.getDeviceId() + "的记录已经已经分配！");
				continue;
			}
			ysObdList.add(ysObd);
		}

		if(ysObdList.size() == 0)
			return 0;

		//插入分配批次与明细
		if(obdAddInDTO.getAgentId()!=null||obdAddInDTO.getShopId()!=null) {
			//插入Group分配批次
			YsObdBatch ysObdDistributionBatch = new YsObdBatch();
			ysObdDistributionBatch.setGroupId(obdAddInDTO.getGroupId());
			ysObdDistributionBatch.setGmtCreate(date);
			ysObdDistributionBatch.setGmtModified(date);
			ysObdDistributionBatch.setCreater(obdAddInDTO.getLoginId());
			ysObdDistributionBatch.setDeviceVersion(obdAddInDTO.getDeviceVersion());
			ysObdDistributionBatch.setOperateType(YunStreamEnum.OBDOperateType.Distribution.getType());//分配
			ysObdDistributionBatch.setBatchNum(ysObdList.size());
			ysObdDistributionBatch.setDistributionTime(date);
			if(obdAddInDTO.getSendAgentId()!=null) {
				ysObdDistributionBatch.setSendAgentId(obdAddInDTO.getSendAgentId());
			}else {
				ysObdDistributionBatch.setSendGroupId(obdAddInDTO.getGroupId());
			}
			ysObdDistributionBatch.setReceiverAgentId(obdAddInDTO.getAgentId());
			ysObdDistributionBatch.setReceiverShopId(obdAddInDTO.getShopId());
			ysObdBatchMapper.insert(ysObdDistributionBatch);

			//插入Group分配批次明细
			for (YsObd ysObd : ysObdList) {
				//插入批次明细
				YsObdBatchItem ysObdDistributionBatchItem = new YsObdBatchItem();
				ysObdDistributionBatchItem.setGroupId(obdAddInDTO.getGroupId());
				ysObdDistributionBatchItem.setGmtCreate(date);
				ysObdDistributionBatchItem.setCreater(obdAddInDTO.getLoginId());
				ysObdDistributionBatchItem.setGmtModified(date);
				ysObdDistributionBatchItem.setBatchId(ysObdDistributionBatch.getId());
				ysObdDistributionBatchItem.setObdId(ysObd.getId());
				ysObdBatchItemMapper.insert(ysObdDistributionBatchItem);
				//更新obd设备分配表
				YsObd recordUpdate = new YsObd();
				recordUpdate.setId(ysObd.getId());
				recordUpdate.setGmtModified(date);
				recordUpdate.setDistributionTime(date);
				recordUpdate.setAgentId(obdAddInDTO.getAgentId());
				recordUpdate.setShopId(obdAddInDTO.getShopId());
				ysObdMapper.updateDistributeOBD(recordUpdate);
			}
		}

		return result;
	}

	@Override
	public ObdShopListOutDTO getShopOBDList(ObdInDTO obdInDTO) throws Exception{
		ObdShopListOutDTO obdShopListOutDTO = new ObdShopListOutDTO();
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId",obdInDTO.getGroupId());
		param.put("shopId",obdInDTO.getShopId());
		param.put("activateStatus",obdInDTO.getActivateStatus());
		param.put("startDate",obdInDTO.getStartDate());
		param.put("endDate",obdInDTO.getEndDate());
		param.put("name", obdInDTO.getName());

		Shop shop = shopMapper.selectByPrimaryKey(obdInDTO.getShopId());
		if(shop == null){
			throw new ApplicationException("门店id"+obdInDTO.getShopId()+"不存在！");
		}
		obdShopListOutDTO.setShopName(shop.getMerchantName());

		int sumCount = ysObdMapper.selectObdShopListCount(param);
		obdShopListOutDTO.setSumCount(sumCount);
		if(sumCount<=0) {
			return obdShopListOutDTO;
		}
		obdShopListOutDTO.setObdNum(sumCount);
		//取得激活数量
		int activateNum = ysObdMapper.selectObdShopActivateCount(param);
		obdShopListOutDTO.setActivateNum(activateNum);
		obdShopListOutDTO.setStoreNum(sumCount - activateNum);

		param.put("limit", obdInDTO.getPageSize());
		param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));

		List<ObdStoreOutDTO> obdStoreOutDTOList = ysObdMapper.selectObdShopList(param);
		List<ObdShopStoreOutDTO> obdShopStoreOutDTOList = new ArrayList<ObdShopStoreOutDTO>();
		for(ObdStoreOutDTO obdStoreOutDTO:obdStoreOutDTOList){
			ObdShopStoreOutDTO obdShopStoreOutDTO = new ObdShopStoreOutDTO();
			BeanUtils.copyProperties(obdShopStoreOutDTO, obdStoreOutDTO);
			obdShopStoreOutDTOList.add(obdShopStoreOutDTO);
		}
		obdShopListOutDTO.setObdShopStoreOutDTOList(obdShopStoreOutDTOList);

		return obdShopListOutDTO;
	}

	@Override
	public ObdAgentListOutDTO getAgentOBDList(ObdInDTO obdInDTO) throws Exception{
		ObdAgentListOutDTO obdAgentListOutDTO = new ObdAgentListOutDTO();
		//取得代理商名称
		Agent agent = agentMapper.selectByPrimaryKey(obdInDTO.getLoginAgentId());
		if(agent == null){
			throw new ApplicationException("代理id"+obdInDTO.getLoginAgentId()+"不存在！");
		}
		obdAgentListOutDTO.setAgentName(agent.getMerchantName());
		obdAgentListOutDTO.setAgentLevel(agent.getAgentLevel());

		//取得子代理商列表
		obdAgentListOutDTO.setAgentList(agentMapper.getAllSubAgentByAgentId(obdInDTO.getLoginAgentId(),obdInDTO.getGroupId()));
		//获取列表数据
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId",obdInDTO.getGroupId());
		param.put("loginAgentId",obdInDTO.getLoginAgentId());
		param.put("agentId",obdInDTO.getAgentId());
		param.put("distributionStatus",obdInDTO.getDistributionStatus());
		param.put("activateStatus",obdInDTO.getActivateStatus());
		param.put("startDate",obdInDTO.getStartDate());
		param.put("endDate",obdInDTO.getEndDate());
		param.put("name", obdInDTO.getName());

		int sumCount = ysObdMapper.selectObdAgentListCount(param);
		obdAgentListOutDTO.setSumCount(sumCount);
		if(sumCount<=0) {
			return obdAgentListOutDTO;
		}
		obdAgentListOutDTO.setObdNum(sumCount);

		param.put("limit", obdInDTO.getPageSize());
		param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));

		List<ObdAgentOutDTO> obdStoreOutDTOList = ysObdMapper.selectObdAgentList(param);
		obdAgentListOutDTO.setObdAgentOutDTOList(obdStoreOutDTOList);
		//计算OBD库存数与激活数量
		int activateNum = 0;
		int storeNum = 0;
		for(ObdAgentOutDTO obdAgentOutDTO:obdStoreOutDTOList){
			if(obdAgentOutDTO.getDistributionStatus() == BizEnum.DistributionStatus.UnDistribution.getType()) {
				storeNum++;
			}
			if(obdAgentOutDTO.getDeviceStatus() != null &&
					obdAgentOutDTO.getDeviceStatus() == YunStreamEnum.OBDActivateStatus.Activated.getType()) {
				activateNum++;
			}
		}
		obdAgentListOutDTO.setStoreNum(storeNum);
		obdAgentListOutDTO.setActivateNum(activateNum);

		return obdAgentListOutDTO;
	}

	@Override
	public int updateObdActivate(String thirdUserId, String deviceId, String activateTime, String sign) throws Exception{
		int result = 0;
		if (Tools.isEmpty(thirdUserId)) {
			throw new ApplicationException(Rescode.FAIL,"memberId 不能为空！");
		}
		if (Tools.isEmpty(deviceId)) {
			throw new ApplicationException(Rescode.FAIL,"deviceId 不能为空！");
		}
		if (Tools.isEmpty(sign)) {
			throw new ApplicationException(Rescode.FAIL,"sign 不能为空！");
		}

		Member member=memberMapper.selectByThirdUserId(thirdUserId);
		if(member==null) {
			throw new ApplicationException(Rescode.FAIL, "会员(memberId:" + thirdUserId + ")不存在！");
		}
        YsObd ysObd = ysObdMapper.selectObdByDeviceId(deviceId);
		if(ysObd==null) {
			throw new ApplicationException(Rescode.FAIL, "设备(deviceId:" + deviceId + ")不存在！");
		}
		if(ysObd.getDeviceStatus() != null && ysObd.getDeviceStatus() == YunStreamEnum.OBDActivateStatus.Activated.getType()){
			throw new ApplicationException(Rescode.FAIL,"设备(deviceId:" + deviceId +")已经激活！");
		}
		ysObd.setActivateUser(member.getId());
		if (Tools.isEmpty(activateTime)) {
			ysObd.setActivateTime(new Date());
			ysObd.setGmtModified(new Date());
		}else{
			ysObd.setActivateTime(DateUtil.fomatDate(activateTime,DateUtil.sdfTime));
			ysObd.setGmtModified(ysObd.getActivateTime());
		}
		if ((ysObd.getAgentId() == null)&&(ysObd.getShopId() == null)) {
			throw new ApplicationException(Rescode.FAIL,"请分配门店或代理");
		}
		ysObd.setDeviceStatus(YunStreamEnum.OBDActivateStatus.Activated.getType());
		if(ysObd.getIsProfit() == null) {
			ysObd.setIsProfit(0);
		}
		result = ysObdMapper.updateByPrimaryKeySelective(ysObd);

		//取得同一用户激活数量(初次激活时建立用户强发展关系)
		int activateCount = ysObdMapper.selectMemberIdActivateCount(member.getId());
		if(activateCount == 1) {
			//更新会员发展关系
			Member memberUpdate = new Member();
			memberUpdate.setId(member.getId());
			if (ysObd.getAgentId() != null) {
				memberUpdate.setFromType(BizEnum.MemberDevelopeFrom.AgentDevelope.getType());
				memberUpdate.setFromId(ysObd.getAgentId());
				memberUpdate.setFromName(agentMapper.selectByPrimaryKey(ysObd.getAgentId()).getMerchantName());
				memberUpdate.setFromMode(BizEnum.MemberDevelopeMode.AppConsume.getType());
				memberUpdate.setGmtModified(new Date());
				result = memberMapper.updateByPrimaryKeySelective(memberUpdate);
			}else if (ysObd.getShopId() != null) {
				memberUpdate.setFromType(BizEnum.MemberDevelopeFrom.ShopDevelope.getType());
				memberUpdate.setFromId(ysObd.getShopId());
				memberUpdate.setFromName(shopMapper.selectByPrimaryKey(ysObd.getShopId()).getMerchantName());
				memberUpdate.setFromMode(BizEnum.MemberDevelopeMode.AppConsume.getType());
				memberUpdate.setGmtModified(new Date());
				result = memberMapper.updateByPrimaryKeySelective(memberUpdate);
			}else{
				throw new ApplicationException(Rescode.FAIL,"请分配门店或代理");
			}

		}else{
            if ((ysObd.getAgentId() == null)&&(ysObd.getShopId() == null)) {
                throw new ApplicationException(Rescode.FAIL,"请分配门店或代理");
            }
        }
        if(ysObd.getIsProfit() == 0) {//未做分润时进入分润计算
			//分润计算处理
			result = profitManageService.insertObdProfitCalculate(member.getId(), ysObd);
		}
		return result;
	}

	@Override
	public YsObdPurchaseSetOutDTO getObdPurchaseParamSettingByGroupId(YsObdPurchaseSet ysObdPurchaseSet) throws ApplicationException {
		YsObdPurchaseSetOutDTO ysObdPurchaseSetOutDTO=new YsObdPurchaseSetOutDTO();

		YsObdPurchaseSet ysObdPurchaseSet1=ysObdPurchaseSetMapper.selectByGroupId(ysObdPurchaseSet.getGroupId());
		if (ysObdPurchaseSet1!=null){
			try{
				PropertyCopyUtil.copyProperties(ysObdPurchaseSet1,ysObdPurchaseSetOutDTO);
			}catch (Exception e){
				ysObdPurchaseSetOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "数据拷贝错误");
			}

		}
		return ysObdPurchaseSetOutDTO;
	}



	@Override
	public BaseOutDTO saveObdPurchaseParamSetting(YsObdPurchaseSet ysObdPurchaseSet) throws ApplicationException {
		BaseOutDTO baseOutDTO=new BaseOutDTO();

		YsObdPurchaseSet ysObdPurchaseSet1=ysObdPurchaseSetMapper.selectByGroupId(ysObdPurchaseSet.getGroupId());
		if (ysObdPurchaseSet1!=null){
			ysObdPurchaseSet.setId(ysObdPurchaseSet1.getId());
			ysObdPurchaseSet.setGmtModified(new Date());
			ysObdPurchaseSetMapper.updateByPrimaryKeySelective(ysObdPurchaseSet);
		}else{
			ysObdPurchaseSet.setGmtCreate(new Date());
			ysObdPurchaseSet.setGmtModified(new Date());
			ysObdPurchaseSetMapper.insert(ysObdPurchaseSet);
		}

		return baseOutDTO;
	}

	@Override
	public int changeOBD(Map<String, Object> param) {
		return ysObdMapper.changeOBD(param);
	}

	@Override
	public int updateOBDByDevice(Map<String, Object> param) {
		return ysObdMapper.updateOBDByDevice(param);
	}

	@Override
	public int insertObdChange(Map<String, Object> param) {
		return ysObdMapper.insertObdChange(param);
	}

	@Override
	public int selectOwnObdByDeviceid(Map<String, Object> param) {
		return ysObdMapper.selectOwnObdByDeviceid(param);
	}

	@Override
	public YsObd selectObdByDeviceId(String deviceId) {
		return ysObdMapper.selectObdByDeviceId(deviceId);
	}


	/**
	 * 这个横向已创建时间统计入库总数
	 * @param map
	 * @return
	 * @throws ApplicationException
	 */
	@Override
	public List getGroupMonthList(Map map) throws ApplicationException {
		return ysObdMapper.getGroupMonthList(map);
	}

	/**
	 * 这个已激活时间统计激活数
	 * @param map
	 * @return
	 */

	@Override
	public List getGroupMonthList2(Map map) {
		return ysObdMapper.getGroupMonthList2(map);
	}

	/**
	 * 统计删除obd数量
	 * @param map
	 * @return
	 * @throws ApplicationException
	 */
	@Override
	public List getGroupMonthList3(Map map) throws ApplicationException {
		return ysObdMapper.getGroupMonthList3(map);
	}

	@Override
	public List<Agent> queryAgentIdsByGroupId(Long groupid, Integer level) {
		return agentMapper.queryAgentIdByGroupId(groupid,level);
	}

	@Override
	public List<Shop> queryShopIdByGroupId(Long groupid) {
		return shopMapper.queryShopIdByGroupId(groupid);
	}

	@Override
	public List<Map<String, Object>> getObdDayList(Map map) throws ApplicationException {
		return ysObdMapper.getObdDayList(map);
	}


	@Override
	public List<Map<String, Object>> getObdMonthList(Map map) throws ApplicationException {
		return ysObdMapper.getObdMonthList(map);
	}


	@Override
	public List queryObdDataReportList(Map map) throws ApplicationException {

		return ysObdMapper.queryObdDataReportList(map);
	}

	@Override
	public ObdDataReportListOutDTO queryAgentOrShopObdList(ObdDataReportInDTO obdDataReportInDTO, Page page) throws ApplicationException {
		ObdDataReportListOutDTO obdDataReportListOutDTO = new ObdDataReportListOutDTO();
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId",obdDataReportInDTO.getGroupId());
		param.put("isProfit",obdDataReportInDTO.getIsProfit());
		param.put("activityStatus",obdDataReportInDTO.getActivityStatus());
		param.put("activityStart",obdDataReportInDTO.getActivityStart());
		param.put("activityEnd",obdDataReportInDTO.getActivityEnd());
		param.put("deviceId",obdDataReportInDTO.getDeviceId());
		param.put("shopId",obdDataReportInDTO.getShopId());
		param.put("agentId",obdDataReportInDTO.getAgentId());

		int sumCount = ysObdMapper.queryAgentOrShopObdCount(param);
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return obdDataReportListOutDTO;

		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));

		List<ObdAgentOrShopOutDTO> obdDataReportOutDTOList = ysObdMapper.queryAgentOrShopObdList(param);
		obdDataReportListOutDTO.setObdAgentOrShopOutDTOList(obdDataReportOutDTOList);
		return obdDataReportListOutDTO;

	}

	//获取obd设备库存列表
	@Override
	public ObdStoreListOutDTO getCancelList(ObdInDTO obdInDTO) throws Exception {
		ObdStoreListOutDTO obdStoreListOutDTO = new ObdStoreListOutDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		if(obdInDTO.getAgentId()!=null){
			param.put("agentId",obdInDTO.getAgentId());
		}
		else if(obdInDTO.getShopId()!=null){
			param.put("shopId",obdInDTO.getShopId());
		}
		else if(obdInDTO.getGroupId()!=null){
			param.put("groupId",obdInDTO.getGroupId());
		}

		//操作员以姓名形式显示
		List<Userbase> userlist = ysObdBatchMapper.selectCreaterList(param);
		for(Userbase ub : userlist) {
			int usertype = ub.getUserType();
			long userid = ub.getId();
			long groupid = ub.getGroupId();
			if(usertype == 1) {//如果是大商户或渠道则去t_group进行姓名查询
				Group group = groupMapper.selectByPrimaryKey(groupid);
				ub.setUsername(group.getMerchantName());
			} else if(usertype == 2||usertype == 3) {//直接取name
				ub.setUsername(ub.getName());
			} else if(usertype == 4) {//代理商
				Agent agent = agentMapper.selectUserId(userid);
				ub.setUsername(agent.getMerchantName());
			} else if(usertype == 5) {//门店
				Shop shop = shopMapper.selectUserId(userid);
				ub.setUsername(shop.getMerchantName());
			}
		}
		//取得入库操作员列表
		obdStoreListOutDTO.setUserbaseList(userlist);
		param.put("groupId",obdInDTO.getGroupId());
		param.put("agentId",obdInDTO.getAgentId());
		param.put("shopId",obdInDTO.getShopId());
		param.put("creater",obdInDTO.getCreater());
		param.put("startDate",obdInDTO.getStartDate());
		param.put("endDate",obdInDTO.getEndDate());
		param.put("name", obdInDTO.getName());

		int sumCount = ysObdMapper.selectObdCancelListCount(param);
		obdStoreListOutDTO.setStoreNum(sumCount);
		obdStoreListOutDTO.setSumCount(sumCount);
		if(sumCount<=0) {
			return obdStoreListOutDTO;
		}
		param.put("limit", obdInDTO.getPageSize());
		param.put("start", obdInDTO.getPageSize()*(obdInDTO.getPageNo()-1));

		List<ObdStoreOutDTO> obdStoreOutDTOList = ysObdMapper.selectObdCancelList(param);
		for(ObdStoreOutDTO osod: obdStoreOutDTOList) {
			long userid = osod.getCreater();
			Userbase ub = userbaseMapper.selectByPrimaryKey(userid);
			int usertype = ub.getUserType();
			long groupid = ub.getGroupId();
			if(usertype == 1) {//如果是大商户或渠道则去t_group进行姓名查询
				Group group = groupMapper.selectByPrimaryKey(groupid);
				osod.setCreaterName(group.getMerchantName());
			} else if(usertype == 2||usertype == 3) {//直接取name
				osod.setCreaterName(ub.getName());
			} else if(usertype == 4) {//代理商
				Agent agent = agentMapper.selectUserId(userid);
				osod.setCreaterName(agent.getMerchantName());
			} else if(usertype == 5) {//门店
				Shop shop = shopMapper.selectUserId(userid);
				osod.setCreaterName(shop.getMerchantName());
			}
		}
		obdStoreListOutDTO.setObdStoreOutDTOList(obdStoreOutDTOList);
		return obdStoreListOutDTO;
	}

	@Override
	public int updateOBDValid(Map param) {
		YsObd obd = new YsObd();
		obd.setDeviceId(param.get("deviceid").toString());
		return ysObdMapper.updateOBDValid(obd);
	}


}

